<?php
namespace app\admin\controller;
use think\Controller;
use think\facade\Db;
use app\admin\controller\Common;
use alipay\AopClient;
use alipay\AlipayUserInfoShareRequest;
use alipay\AlipaySystemOauthTokenRequest;
use app\admin\controller\Room;
use app\service\roomService;
use app\service\lockService;
class Apiuser extends Controller{
    const PRIKEYPATH = 'C:\phpStudy\PHPTutorial\WWW\entrance\prikey.txt';//私钥路径
    const PUBKEYPATH = 'C:\phpStudy\PHPTutorial\WWW\entrance\pubkey.txt';//支付宝公钥路径
    public function apiuser($serial){
        $app_id = request()->get('app_id');
        $source = request()->get('source');
        $scope = request()->get('scope');
        $auth_code = request()->get('auth_code');

        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2018090361235311';
        $aop->rsaPrivateKey = file_get_contents(self::PRIKEYPATH);
        $aop->alipayrsaPublicKey= file_get_contents(self::PUBKEYPATH);
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';

        $request = new AlipaySystemOauthTokenRequest ();
        $request->setGrantType('authorization_code');
        $request->setCode($auth_code);
        $request->setRefreshToken('');
        $result = $aop->execute ($request);

        if(property_exists($result,'error_response')){
            $responseNode = 'error_response';
        }else{
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";   
        }
        //判断是否为提交页面
        if(request()->isPost()){
            $userid = request()->get('userid');
        }else{
            $userid = $result->$responseNode->user_id;
        }
        // $userid = 201833;
        //根据支付宝ID和当前锁ID查询是否一验证该锁
        $useridinfo = (new roomService())->userIdInfo($userid,$serial);
        if(!empty($useridinfo)){
            //根据门锁ID查询小区信息
            $serialcommunity = (new roomService())->serialCommunity($serial);
            if(empty($serialcommunity)){
                $this->error('二维码错误',url('index/Index/index'));
            }
            //根据小区ID查找小区信息
            $communityidinfo = (new roomService())->communityIdInfo($serialcommunity);
            //传入物业ID，门锁ID，操作ID
            $doorreturn = (new Door())->door($communityidinfo['property'],$serial,4);
            //判断是否开锁成功
            if($doorreturn['state'] == 1){
                //添加开门记录信息
                $record['community'] = $serialcommunity;
                //根据房屋ID查询房屋信息
                $roomidinfo = (new roomService())->roomIdInfo($useridinfo['room_id']);
                $record['address'] = $roomidinfo['group'].$roomidinfo['building'].'幢'.$roomidinfo['unit'].'单元'.$roomidinfo['room'].'室';
                $record['name'] = $useridinfo['name'];
                $record['phone'] = $useridinfo['phone'];
                $record['alipay'] = $userid;
                $record['serial'] = $serial;
                $record['time'] = date('Y-m-d H:i:s',time());
                $recordadd = (new roomService())->recordAdd($record);
				$url="https://s.click.taobao.com/HKPaUtv";//https://s.click.taobao.com/xOjO4xv
				echo "<script>alert('开门成功,欢迎回家');location.href='$url'</script>";
				exit;
                //$this->success('开门成功，（微信关注《早早番茄》上传人脸识别）',url('index/Index/index'));
				return View::fetch("opensuccess");
				//$url=url('index/Index/opensuccess');
				//echo "<script>location.href='$url';</script>";
            }else{
				return View::fetch("openfail");
                //$this->error('开门失败，重新扫码',url('index/Index/index'));
            }
        }else{
            //判断是否已提交申请
            $useridstatusinfo = (new roomService())->userIdStatusInfo($userid,$serial);
            if(isset($useridstatusinfo)){
                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
            }
            //根据门锁ID查询小区信息
            $community = (new roomService())->communitySerialInfo($serial);
            View::assign('communitylist',$community);
            View::assign('userid',$userid);
            View::assign('serial',$serial);
            //验证信息，1：小区大门锁:，2：单元楼栋锁
            //根据门锁查询门锁类型
            $locktype = (new roomService())->lockType($serial);
            if($locktype == 1){
                if(request()->isPost()){
                    //获取表单数据
                    $data = request()->post();
					
                    // dump($data);exit();
                    //查询所选房号数据
                    $roominfo = (new roomService())->roomInfo($data['community'],$data['group'],$data['building'],$data['unit'],$data['room']);
					
                    //验证信息是否正确
                    if($data['relation'] == 1){
                        //业主，直接验证预留号码信息，默认永久有效
                        if($data['name'] == $roominfo['name']){
                            if($data['phone'] == $roominfo['phone']){
                                $proving = (new roomService())->provingInfo($data['phone']);
                                if($data['number'] == $proving){
                                    //判断业主是否已经存在
                                    $personnelinfo = (new roomService())->personnelInfo($community['id'],$roominfo['id'],1);
                                    if(isset($personnelinfo)){
                                        $this->error('该房号已有业主，请选择其他关系',url('index/Index/index'));
                                    }
                                    $personnel['community'] = $community['id'];
                                    $personnel['room_id'] = $roominfo['id'];
                                    $personnel['relation'] = 1;
                                    $personnel['name'] = $data['name'];
                                    $personnel['phone'] = $data['phone'];
                                    $personnel['alipay'] = $userid;
                                    //查询楼栋锁
                                    $unitlock = (new roomService())->unitLock($roominfo['id']);
                                    //查询小区大门所有锁
                                    $communitylock = implode(',',(new roomService())->communityLock($personnel['community']));
                                    $personnel['serial'] = $communitylock.','.$unitlock;
                                    $personnel['status'] = 1;
                                    $personnel['in_time'] = date('Y-m-d H:i:s',time());
                                    $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+3years",strtotime(date('Y-m-d H:i:s',time()))));
                                    $personneladd = (new roomService())->personnelAdd($personnel);
                                    if($personneladd){
                                        //开门
                                        $doorreturn = (new Door())->door($community['property'],$serial,4);
                                        if($doorreturn['state'] == 1){
                                            //添加开门记录信息
                                            $record['community'] = $community['id'];
                                            $record['serial'] = $serial;
                                            //根据房屋ID查询房屋信息
                                            $roomidinfo = (new roomService())->roomIdInfo($roominfo['id']);
                                            $record['address'] = $roomidinfo['group'].$roomidinfo['building'].'幢'.$roomidinfo['unit'].'单元'.$roomidinfo['room'].'室';
                                            $record['name'] = $roominfo['name'];
                                            $record['phone'] = $roominfo['phone'];
                                            $record['alipay'] = $userid;
                                            $record['time'] = date('Y-m-d H:i:s',time());
                                            $recordadd = (new roomService())->recordAdd($record);
                                            $this->success('开门成功',url('index/Index/index'));
                                        }else{
                                            $this->error('开门失败',url('index/Index/index'));
                                        }
                                    }else{
                                        $this->error('提交失败，重新扫码申请',url('index/Index/index'));
                                    }
                                }else{
                                    $this->error('验证码错误，请重新扫码验证',url('index/Index/index')); 
                                }
                            }else{
                                $this->error('手机号错误，请重新扫码验证',url('index/Index/index')); 
                            }
                        }else{
                            $this->error('姓名错误，请重新扫码验证',url('index/Index/index'));
                        }
                    }else if($data['relation'] == 2){
                        //家人，提交给业主允许，默认永久
                        $proving = (new roomService())->provingInfo($data['phone']);
                        if($data['number'] == $proving){
                            //未添加，添加用户
                            $personnel['community'] = $community['id'];
                            $personnel['room_id'] = $roominfo['id'];
                            $personnel['relation'] = 2;
                            $personnel['name'] = $data['name'];
                            $personnel['phone'] = $data['phone'];
                            $personnel['alipay'] = $userid;
                            //查询楼栋锁
                            $unitlock = (new roomService())->unitLock($roominfo['id']);
                            //查询小区大门所有锁
                            $communitylock = implode(',',(new roomService())->communityLock($personnel['community']));
                            $personnel['serial'] = $communitylock.','.$unitlock;
                            $personnel['status'] = 2;
                            $personnel['in_time'] = date('Y-m-d H:i:s',time());
                            $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+1years",strtotime(date('Y-m-d H:i:s',time()))));
                            $personneladd = (new roomService())->personnelAdd($personnel);
                            if(empty($personneladd)){
                                $this->error('信息填写错误，请重新填写提交申请',url('index/Index/index'));
                            }else{
                                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
                            }
                        }else{
                            $this->error('验证码错误，请重新扫码验证',url('index/Index/index')); 
                        }
                    }else if($data['relation'] == 3){
                        //租客，提交给业主允许，默认三个月
                        $proving = (new roomService())->provingInfo($data['phone']);
                        if($data['number'] == $proving){
                            $personnel['community'] = $community['id'];
                            $personnel['room_id'] = $roominfo['id'];
                            $personnel['relation'] = 3;
                            $personnel['name'] = $data['name'];
                            $personnel['phone'] = $data['phone'];
                            $personnel['alipay'] = $userid;
                            //查询楼栋锁
                            $unitlock = (new roomService())->unitLock($roominfo['id']);
                            //查询小区大门所有锁
                            $communitylock = implode(',',(new roomService())->communityLock($personnel['community']));
                            $personnel['serial'] = $communitylock.','.$unitlock;
                            $personnel['status'] = 2;
                            $personnel['in_time'] = date('Y-m-d H:i:s',time());
                            $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+3months",strtotime(date('Y-m-d H:i:s',time()))));
                            $personneladd = (new roomService())->personnelAdd($personnel);
                            if(empty($personneladd)){
                                $this->error('信息填写错误，请重新填写提交申请',url('index/Index/index'));
                            }else{
                                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
                            }
                        }else{
                            $this->error('验证码错误，请重新扫码验证',url('index/Index/index')); 
                        }
                    }else if($data['relation'] == 4){
                        //访客，提交给业主允许，默认一小时
                        $proving = (new roomService())->provingInfo($data['phone']);
                        if($data['number'] == $proving){
                            $personnel['community'] = $community['id'];
                            $personnel['room_id'] = $roominfo['id'];
                            $personnel['relation'] = 4;
                            $personnel['name'] = $data['name'];
                            $personnel['phone'] = $data['phone'];
                            $personnel['alipay'] = $userid;
                            //查询楼栋锁
                            $unitlock = (new roomService())->unitLock($roominfo['id']);
                            //查询小区大门所有锁
                            $communitylock = implode(',',(new roomService())->communityLock($personnel['community']));
                            $personnel['serial'] = $communitylock.','.$unitlock;
                            $personnel['status'] = 2;
                            $personnel['in_time'] = date('Y-m-d H:i:s',time());
                            $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+1hours",strtotime(date('Y-m-d H:i:s',time()))));
                            $personneladd = (new roomService())->personnelAdd($personnel);
                            if(empty($personneladd)){
                                $this->error('信息填写错误，请重新填写提交申请',url('index/Index/index'));
                            }else{
                                $result = (new Letter())->sendOutNotice($roominfo['phone']);
                                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
                            }
                        }else{
                            $this->error('验证码错误，请重新扫码验证',url('index/Index/index')); 
                        }
                    }
                }
                return View::fetch('verification');
            }elseif($locktype == 2){
                if(request()->isPost()){
                    //获取表单数据
                    $data = request()->post();
                    //查询所选房号数据
                    $roominfo = (new roomService())->roomInfo($data['community'],$data['group'],$data['building'],$data['unit'],$data['room']);
                    //验证信息是否正确
                    if($data['relation'] == 1){
                        //业主，直接验证预留号码信息，默认永久有效
                        if($data['name'] == $roominfo['name']){
                            if($data['phone'] == $roominfo['phone']){
                                $proving = (new roomService())->provingInfo($data['phone']);
                                if($data['number'] == $proving){
                                    //判断业主是否已经存在
                                    $personnelinfo = (new roomService())->personnelInfo($community['id'],$roominfo['id'],1);
                                    if(isset($personnelinfo)){
                                        $this->error('该房号已有业主，请选择其他关系',url('index/Index/index'));
                                    }
                                    //添加用户
                                    $personnel['community'] = $community['id'];
                                    $personnel['room_id'] = $roominfo['id'];
                                    $personnel['relation'] = 1;
                                    $personnel['name'] = $data['name'];
                                    $personnel['phone'] = $data['phone'];
                                    $personnel['alipay'] = $userid;
                                    //查询楼栋锁
                                    $unitlock = (new roomService())->unitLock($roominfo['id']);
                                    //查询小区大门所有锁
                                    $communitylock = implode(',',(new roomService())->communityLock($personnel['community']));
                                    $personnel['serial'] = $communitylock.','.$unitlock;
                                    $personnel['status'] = 1;
                                    $personnel['in_time'] = date('Y-m-d H:i:s',time());
                                    $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+3years",strtotime(date('Y-m-d H:i:s',time()))));
                                    $personneladd = (new roomService())->personnelAdd($personnel);
                                    if($personneladd){
                                        //开门
                                        $doorreturn = (new Door())->door($community['property'],$serial,4);
                                        if($doorreturn['state'] == 1){
                                            //添加开门记录信息
                                            $record['community'] = $community['id'];
                                            $record['serial'] = $serial;
                                            //根据房屋ID查询房屋信息
                                            $roomidinfo = (new roomService())->roomIdInfo($roominfo['id']);
                                            $record['address'] = $roomidinfo['group'].$roomidinfo['building'].'幢'.$roomidinfo['unit'].'单元'.$roomidinfo['room'].'室';
                                            $record['name'] = $roominfo['name'];
                                            $record['phone'] = $roominfo['phone'];
                                            $record['alipay'] = $userid;
                                            $record['time'] = date('Y-m-d H:i:s',time());
                                            $recordadd = (new roomService())->recordAdd($record);
                                            $this->success('开门成功',url('index/Index/index'));
                                        }else{
                                            $this->error('开门失败',url('index/Index/index'));
                                        }
                                    }else{
                                        $this->error('提交失败，重新扫码申请',url('index/Index/index'));
                                    }
                                }else{
                                    $this->error('验证码错误，请重新扫码验证',url('index/Index/index')); 
                                }
                            }else{
                                $this->error('手机号错误，请重新扫码验证',url('index/Index/index')); 
                            }
                        }else{
                            $this->error('姓名错误，请重新扫码验证',url('index/Index/index'));
                        }
                    }else if($data['relation'] == 2){
                        //家人，提交给业主允许，默认永久
                        $proving = (new roomService())->provingInfo($data['phone']);
                        if($data['number'] == $proving){
                            $personnel['community'] = $community['id'];
                            $personnel['room_id'] = $roominfo['id'];
                            $personnel['relation'] = 2;
                            $personnel['name'] = $data['name'];
                            $personnel['phone'] = $data['phone'];
                            $personnel['alipay'] = $userid;
                            //查询楼栋锁
                            $unitlock = (new roomService())->unitLock($roominfo['id']);
                            //查询小区大门所有锁
                            $communitylock = implode(',',(new roomService())->communityLock($personnel['community']));
                            $personnel['serial'] = $communitylock.','.$unitlock;
                            $personnel['status'] = 2;
                            $personnel['in_time'] = date('Y-m-d H:i:s',time());
                            $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+1years",strtotime(date('Y-m-d H:i:s',time()))));
                            $personneladd = (new roomService())->personnelAdd($personnel);
                            if(empty($personneladd)){
                                $this->error('信息填写错误，请重新填写提交申请',url('index/Index/index'));
                            }else{
                                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
                            }
                        }else{
                            $this->error('验证码错误，请重新扫码验证',url('index/Index/index'));
                        }
                    }else if($data['relation'] == 3){
                        //租客，提交给业主允许，默认三个月
                        $proving = (new roomService())->provingInfo($data['phone']);
                        if($data['number'] == $proving){
                            $personnel['community'] = $community['id'];
                            $personnel['room_id'] = $roominfo['id'];
                            $personnel['relation'] = 3;
                            $personnel['name'] = $data['name'];
                            $personnel['phone'] = $data['phone'];
                            $personnel['alipay'] = $userid;
                            //查询楼栋锁
                            $unitlock = (new roomService())->unitLock($roominfo['id']);
                            //查询小区大门所有锁
                            $communitylock = implode(',',(new roomService())->communityLock($personnel['community']));
                            $personnel['serial'] = $communitylock.','.$unitlock;
                            $personnel['status'] = 2;
                            $personnel['in_time'] = date('Y-m-d H:i:s',time());
                            $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+3months",strtotime(date('Y-m-d H:i:s',time()))));
                            $personneladd = (new roomService())->personnelAdd($personnel);
                            if(empty($personneladd)){
                                $this->error('信息填写错误，请重新填写提交申请',url('index/Index/index'));
                            }else{
                                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
                            }
                        }else{
                            $this->error('验证码错误，请重新扫码验证',url('index/Index/index'));
                        }
                    }else if($data['relation'] == 4){
                        //访客，提交给业主允许，默认一小时
                        $proving = (new roomService())->provingInfo($data['phone']);
                        if($data['number'] == $proving){
                            $personnel['community'] = $community['id'];
                            $personnel['room_id'] = $roominfo['id'];
                            $personnel['relation'] = 4;
                            $personnel['name'] = $data['name'];
                            $personnel['phone'] = $data['phone'];
                            $personnel['alipay'] = $userid;
                            //查询楼栋锁
                            $unitlock = (new roomService())->unitLock($roominfo['id']);
                            //查询小区大门所有锁
                            $communitylock = implode(',',(new roomService())->communityLock($personnel['community']));
                            $personnel['serial'] = $communitylock.','.$unitlock;
                            $personnel['status'] = 2;
                            $personnel['in_time'] = date('Y-m-d H:i:s',time());
                            $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+1hours",strtotime(date('Y-m-d H:i:s',time()))));
                            $personneladd = (new roomService())->personnelAdd($personnel);
                            if(empty($personneladd)){
                                $this->error('信息填写错误，请重新填写提交申请',url('index/Index/index'));
                            }else{
                                $result = (new Letter())->sendOutNotice($roominfo['phone']);
                                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
                            }
                        }else{
                            $this->error('验证码错误，请重新扫码验证',url('index/Index/index'));
                        }
                    }
                }
                return View::fetch('verification');
            }elseif($locktype == 3){
                if(request()->isPost()){
                    //获取表单数据
                    $data = request()->post();
                    //查询所选房号数据
                    $roominfo = (new roomService())->roomInfo($data['community'],$data['group'],$data['building'],$data['unit'],$data['room']);
                    //验证信息是否正确
                    if($data['relation'] == 1){
                        //业主，直接验证预留号码信息，默认永久有效
                        if($data['name'] == $roominfo['name']){
                            if($data['phone'] == $roominfo['phone']){
                                $proving = (new roomService())->provingInfo($data['phone']);
                                if($data['number'] == $proving){
                                    //判断业主是否已经存在
                                    $personnelinfo = (new roomService())->personnelInfo($community['id'],$roominfo['id'],1);
                                    if(isset($personnelinfo)){
                                        $this->error('该房号已有业主，请选择其他关系',url('index/Index/index'));
                                    }
                                    //判断当前用户是否已添加
                                    $useridpersonnelinfo = (new roomService())->userIdPersonnelInfo($userid,$roominfo['id']);
                                    if(isset($useridpersonnelinfo)){
                                        //已添加，修改用户
                                        //查询小区大门所有锁
                                        $communitylock = implode(',',(new roomService())->communityLock($data['community']));
                                        //查询别墅小门所有锁
                                        $villalock = implode(',',(new roomService())->villaLock($data['community']));
                                        $personnel['serial'] = $communitylock.','.$villalock;
                                        $personnel['id'] = $useridpersonnelinfo['id'];
                                        $personneladd = (new roomService())->personnelEdit($personnel);
                                    }else{
                                        //添加用户
                                        $personnel['community'] = $community['id'];
                                        $personnel['room_id'] = $roominfo['id'];
                                        $personnel['relation'] = 1;
                                        $personnel['name'] = $data['name'];
                                        $personnel['phone'] = $data['phone'];
                                        $personnel['alipay'] = $userid;
                                        //查询小区大门所有锁
                                        $communitylock = implode(',',(new roomService())->communityLock($data['community']));
                                        //查询别墅小门所有锁
                                        $villalock = implode(',',(new roomService())->villaLock($data['community']));
                                        $personnel['serial'] = $communitylock.','.$villalock;
                                        $personnel['status'] = 1;
                                        $personnel['in_time'] = date('Y-m-d H:i:s',time());
                                        $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+3years",strtotime(date('Y-m-d H:i:s',time()))));
                                    }
                                    $personneladd = (new roomService())->personnelAdd($personnel);
                                    if($personneladd){
                                        //开门
                                        $doorreturn = (new Door())->door($community['property'],$serial,4);
                                        if($doorreturn['state'] == 1){
                                            //添加开门记录信息
                                            $record['community'] = $community['id'];
                                            $record['serial'] = $serial;
                                            //根据房屋ID查询房屋信息
                                            $roomidinfo = (new roomService())->roomIdInfo($roominfo['id']);
                                            $record['address'] = $roomidinfo['group'].$roomidinfo['building'].'幢'.$roomidinfo['unit'].'单元'.$roomidinfo['room'].'室';
                                            $record['name'] = $roominfo['name'];
                                            $record['phone'] = $roominfo['phone'];
                                            $record['alipay'] = $userid;
                                            $record['time'] = date('Y-m-d H:i:s',time());
                                            $recordadd = (new roomService())->recordAdd($record);
                                            $this->success('开门成功',url('index/Index/index'));
                                        }else{
                                            $this->error('开门失败',url('index/Index/index'));
                                        }
                                    }else{
                                        $this->error('提交失败，重新扫码申请',url('index/Index/index'));
                                    }
                                }else{
                                    $this->error('验证码错误，请重新扫码验证',url('index/Index/index')); 
                                }
                            }else{
                                $this->error('手机号错误，请重新扫码验证',url('index/Index/index')); 
                            }
                        }else{
                            $this->error('姓名错误，请重新扫码验证',url('index/Index/index'));
                        }
                    }else if($data['relation'] == 2){
                        //家人，提交给业主允许，默认永久
                        $proving = (new roomService())->provingInfo($data['phone']);
                        if($data['number'] == $proving){
                            $personnel['community'] = $community['id'];
                            $personnel['room_id'] = $roominfo['id'];
                            $personnel['relation'] = 2;
                            $personnel['name'] = $data['name'];
                            $personnel['phone'] = $data['phone'];
                            $personnel['alipay'] = $userid;
                            //查询小区大门所有锁
                            $communitylock = implode(',',(new roomService())->communityLock($data['community']));
                            //查询别墅小门所有锁
                            $villalock = implode(',',(new roomService())->villaLock($data['community']));
                            $personnel['serial'] = $communitylock.','.$villalock;
                            $personnel['status'] = 2;
                            $personnel['in_time'] = date('Y-m-d H:i:s',time());
                            $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+1years",strtotime(date('Y-m-d H:i:s',time()))));
                            $personneladd = (new roomService())->personnelAdd($personnel);
                            if(empty($personneladd)){
                                $this->error('信息填写错误，请重新填写提交申请',url('index/Index/index'));
                            }else{
                                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
                            }
                        }else{
                            $this->error('验证码错误，请重新扫码验证',url('index/Index/index'));
                        }
                    }else if($data['relation'] == 3){
                        //租客，提交给业主允许，默认三个月
                        $proving = (new roomService())->provingInfo($data['phone']);
                        if($data['number'] == $proving){
                            $personnel['community'] = $community['id'];
                            $personnel['room_id'] = $roominfo['id'];
                            $personnel['relation'] = 3;
                            $personnel['name'] = $data['name'];
                            $personnel['phone'] = $data['phone'];
                            $personnel['alipay'] = $userid;
                            //查询小区大门所有锁
                            $communitylock = implode(',',(new roomService())->communityLock($data['community']));
                            //查询别墅小门所有锁
                            $villalock = implode(',',(new roomService())->villaLock($data['community']));
                            $personnel['serial'] = $communitylock.','.$villalock;
                            $personnel['status'] = 2;
                            $personnel['in_time'] = date('Y-m-d H:i:s',time());
                            $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+3months",strtotime(date('Y-m-d H:i:s',time()))));
                            $personneladd = (new roomService())->personnelAdd($personnel);
                            if(empty($personneladd)){
                                $this->error('信息填写错误，请重新填写提交申请',url('index/Index/index'));
                            }else{
                                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
                            }
                        }else{
                            $this->error('验证码错误，请重新扫码验证',url('index/Index/index'));
                        }
                    }else if($data['relation'] == 4){
                        //访客，提交给业主允许，默认一小时
                        $proving = (new roomService())->provingInfo($data['phone']);
                        if($data['number'] == $proving){
                            $personnel['community'] = $community['id'];
                            $personnel['room_id'] = $roominfo['id'];
                            $personnel['relation'] = 4;
                            $personnel['name'] = $data['name'];
                            $personnel['phone'] = $data['phone'];
                            $personnel['alipay'] = $userid;
                            //查询小区大门所有锁
                            $communitylock = implode(',',(new roomService())->communityLock($data['community']));
                            //查询别墅小门所有锁
                            $villalock = implode(',',(new roomService())->villaLock($data['community']));
                            $personnel['serial'] = $communitylock.','.$villalock;
                            $personnel['status'] = 2;
                            $personnel['in_time'] = date('Y-m-d H:i:s',time());
                            $personnel['out_time'] = date("Y-m-d H:i:s",strtotime("+1hours",strtotime(date('Y-m-d H:i:s',time()))));
                            $personneladd = (new roomService())->personnelAdd($personnel);
                            if(empty($personneladd)){
                                $this->error('信息填写错误，请重新填写提交申请',url('index/Index/index'));
                            }else{
                                $result = (new Letter())->sendOutNotice($roominfo['phone']);
                                $this->success('已提交申请，请联系业主审核',url('index/Index/index'));
                            }
                        }else{
                            $this->error('验证码错误，请重新扫码验证',url('index/Index/index'));
                        }
                    }
                }
                return View::fetch('verification');
            }else{
                $this->error('链接错误',url('index/Index/index'));
            }
        }
    }
    //业主审批
    public function personnelapproval(){
        //获取业主支付宝账号
        $app_id = request()->get('app_id');
        $auth_code = request()->get('auth_code');

        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2018090361235311';
        $aop->rsaPrivateKey = file_get_contents(self::PRIKEYPATH);
        $aop->alipayrsaPublicKey= file_get_contents(self::PUBKEYPATH);
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';

        $request = new AlipaySystemOauthTokenRequest ();
        $request->setGrantType('authorization_code');
        $request->setCode($auth_code);
        $request->setRefreshToken('');
        $result = $aop->execute ($request);

        if(property_exists($result,'error_response')){
            $responseNode = 'error_response';
        }else{
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";   
        }
        if(property_exists($result->$responseNode,'sub_msg')){
            return json(['info' => $result->$responseNode->sub_msg]);
        }
        $userid = $result->$responseNode->user_id;
        //根据业主支付宝账号查询房屋
        $roomidlist = array_unique((new roomService())->roomIdList($userid));
        if(empty($roomidlist)){
            $this->error('亲！如果有您的审核信息我们会通知您！');
        }
        foreach($roomidlist as $roomid){
            //根据房屋查询待审批用户
            $personnellist = (new roomService())->personnelAllowList($roomid);
            foreach($personnellist as $per){
                //根据小区编号查询小区名称
                $comid = $per['community'];
                $community = (new roomService())->communityName($comid);
                $per['community'] = $community['name'];
                //根据房号查询信息
                $roomidinfo = (new roomService())->roomIdInfo($per['room_id']);
                $per['room_id'] = $roomidinfo['group'].$roomidinfo['building'].'幢'.$roomidinfo['unit'].'单元'.$roomidinfo['room'].'室';
                $list[] = $per;
            }  
        }
        // dump($list);exit();
        if(isset($list)){
            View::assign('list',$list);
        }else{
            View::assign('list',$personnellist);
        }
        $number = count($personnellist);
        View::assign('number',$number);
        return View::fetch('personne_allow');
    }
    //处理结果
    public function personnelresult(){
        $id = request()->param('id');
        $type = request()->param('type');
        // dump($id);
        //判断是否存在该数据
        $info = (new roomService())->personnelIdinfo($id);
        if(empty($info)){
            $this->error('该人员请求不存在');
        }
        // dump($id);dump($type);exit();
        if($type == 1){
            $result = (new roomService())->personnelIdAllow($id);
            $content = '您已通过，请重新扫一扫进入小区，祝您生活愉快';
        }elseif($type == 2){
            $result = (new roomService())->personnelIdDel($id);
            $content = '您未通过，请重新扫一扫进行认证，祝您生活愉快';
        }
        if($result){
            $sendresult = (new Letter())->sendOutResult($info['phone'],$content);
            $this->success('处理成功',url('index/Index/index'));
        }else{
            $this->success('处理失败',url('index/Index/index'));
        }
    }
    //手机验证码
    public function personnel(){
        if(request()->isPost()){
            $data['phone'] = request()->Post('phone');
            $data['number'] = rand(100000,999999);
            $data['time'] = date('Y-m-d H:i:s',time());
            $provingadd = (new roomService())->provingAdd($data);
            $result = (new Letter())->sendOut($data['phone'],$data['number']);
            if($result == 1){
                return json(['code' => 1, 'info' => '短信发送成功']);
            }else{
                return json(['code' => 0, 'info' => '短信发送失败']);
            }
        }else{
            return json(['code' => 0, 'info' => '短信发送失败']);
        }
    }
    //查询房屋
    public  function fetchdata(){
        $type = request()->post('type');
        switch($type) {
            case 1:
                $community = request()->post('community');
                $group = array_unique((new lockService())->groupList($community));
                return array_values($group);
            case 2:
                $community = request()->post('community');
                $group = request()->post('group');
                $building = array_unique((new lockService())->buildingList($community,$group));
                return array_values($building);
            case 3:
                $community = request()->post('community');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = array_unique((new lockService())->unitList($community,$group,$building));
                return array_values($unit);
            case 4:
                $community = request()->post('community');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = request()->post('unit');
                $room = array_unique((new lockService())->roomList($community,$group,$building,$unit));
                return array_values($room);
            default:
                return json(['info' => '查询错误']);
        }
    }
    //人员管理
    public function personnelList(){
        //根据当前账号查询小区
        $com = (new Common())->pidTokenId();
        $communitylist = (new roomService())->communityList($com);
        foreach($communitylist as $val){
            $commuid[] = $val['id'];
        }
         
        if(isset($commuid)){
            $community = implode(',',$commuid);
        }else{
            $community = null;
        }

        View::assign('communitylist',$communitylist);
        //多条件查询
        $data = request()->get();
        if (!empty($data['community_id'])){
            $groups = array_unique((new lockService())->groupList($data['community_id']));
            View::assign('groups', array_values($groups));
            // dump($data['group']);
            if (!empty($data['group'])) {
                $buildings = array_unique((new lockService())->buildingList($data['community_id'],$data['group']));
                View::assign('buildings', array_values($buildings));
                // dump($buildings);exit();
                if (!empty($data['building'])) {
                    $units = array_unique((new lockService())->unitList($data['community_id'], $data['group'],$data['building']));
                    View::assign('units', array_values($units));

                    if(!empty($data['unit'])){
                        $rooms = array_unique((new lockService())->roomList($data['community_id'], $data['group'],$data['building'],$data['unit']));
                        View::assign('rooms', array_values($rooms));
                    }
                }
            }
        }
        $whereroom = [];
        $where = [];
        if(!empty($data)){
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];
            }else{
                $where['community_id'] = "";
            }
            if(!empty($data['group'])){
                $whereroom['group'] = $data['group'];
            }else{
                $whereroom['group'] = "";
            }
            if(!empty($data['building'])){
                $whereroom['building'] = $data['building'];
            }else{
                $whereroom['building'] = "";
            }
            if(!empty($data['unit'])){
                $whereroom['unit'] = $data['unit'];
            }else{
                $whereroom['unit'] = "";
            }
            if(!empty($data['room'])){
                $whereroom['room'] = $data['room'];
            }else{
                $whereroom['room'] = "";
            }
            if(!empty($data['name'])){
                $where['name'] = $data['name'];
            }else{
                $where['name'] = "";
            }
            if(!empty($data['phone'])){
                $where['phone'] = $data['phone'];
            }else{
                $where['phone'] = "";
            }
            if(!empty($data['relation'])){
                $where['relation'] = $data['relation'];
            }else{
                $where['relation'] = "";
            }
            if(!empty($data['serial'])){
                $where['serial'] = $data['serial'];
            }else{
                $where['serial'] = "";
            }
            if(!empty($data['status'])){
                $where['status'] = $data['status'];
            }else{
                $where['status'] = "";
            }
        }
        //die;
        $whereroom = array_filter($whereroom);
        //查询房号
        if(!empty($whereroom)){
            $where['room_id'] = array('in',(new roomService())->whereRoom($community,$whereroom));
        }
        $where = array_filter($where);
        // dump($whereroom);dump($where);exit();
        $page = request()->has('page') ? request()->get('page') : 1;
        //查询房屋条数
        $number = (new roomService())->personnelListNumber($community,$where);
        $number = count($number);
        View::assign('number',$number);

        //查询房屋信息
        $personnellist = (new roomService())->personnelList($community,$page,$where);

        foreach($personnellist as $personnel){
            //根据小区编号查询小区名称
            $comid = $personnel['community_id'];
            $community = (new roomService())->communityName($comid);
            $personnel['community_id'] = $community['name'];
            //根据房号查询信息
            $roomidinfo = (new roomService())->roomIdInfo($personnel['room_id']);
            $personnel['room_id'] = $roomidinfo['group'].$roomidinfo['building'].'幢'.$roomidinfo['unit'].'单元'.$roomidinfo['room'].'室';
            $list[] = $personnel;
        }
        if(!isset($list)){
            View::assign('list',$personnellist);
        }else{
            View::assign('list',$list);
        }
        View::assign('personnellist',$personnellist);
        foreach($whereroom as $k => $v) {
            View::assign($k, $v);
        }
        foreach($where as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch('personnel_list');
    }
	//删除
	public function propertyDel(){
        $id = $_GET['id'];
        $del = Db::name('personnel')->delete(['id'=>$id]);
        if($del){
            $this->success('删除成功',url('personnelList'));
        }else{
            $this->success('处理失败',url('personnelList'));
        }

    }
	
	
	
	public function getgroup(){
        $communityid=request()->param("communityid");
        $group=Db::table('room')->distinct(true)->field('group')->where("community",$communityid)->select();
        $str="<option value=''>请选择组团</option>";
        foreach ($group as $key => $value) {
           $str=$str."<option value='".$value["group"]."'>".$value["group"]."</option>";
        }
        echo $str;
    }

    public function getbuilding(){
        $communityid=request()->param("communityid");
        $group=request()->param("group");
        $building=Db::table('room')->distinct(true)->field('building')->where("community",$communityid)->where("group",$group)->select();
        $str="<option value=''>请选择幢号</option>";
        foreach ($building as $key => $value) {
           $str=$str."<option value='".$value["building"]."'>".$value["building"]."幢</option>";
        }
        echo $str;
    }
    public function getunit(){
        $communityid=request()->param("communityid");
        $group=request()->param("group");
        $building=request()->param("building");
        $unit=Db::table('room')->distinct(true)->field('unit')->where("community",$communityid)->where("group",$group)->where("building",$building)->select();
        $str="<option value=''>请选择单元</option>";
        foreach ($unit as $key => $value) {
           $str=$str."<option value='".$value["unit"]."'>".$value["unit"]."单元</option>";
        }
        echo $str;
    }
    public function getroomid(){
        $communityid=request()->param("communityid");
        $group=request()->param("group");
        $building=request()->param("building");
        $unit=request()->param("unit");
        $roomid=Db::table('room')->field('id,room')->where("community",$communityid)->where("group",$group)->where("building",$building)->where("unit",$unit)->select();
        $str="<option value=''>请选择房间号</option>";
        foreach ($roomid as $key => $value) {
           $str=$str."<option value='".$value["room"]."'>".$value["room"]."</option>";
        }
        echo $str;
    }
	
}